// 中间件来验证token
const {JWT_SECRET} =require('../config/userConfig')
const jwt = require('jsonwebtoken');
// 用于验证JWT的中间件
const WHITELISTED_ROUTES = ['/login', '/status', '/register'];
function authenticateToken(req, res, next) {
    // 检查白名单
  if (WHITELISTED_ROUTES.includes(req.originalUrl)) {
    return next();
  }
  // 从请求头中获取token
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // 格式应该是 "Bearer TOKEN"
  if (token == null) {
    return res.json({
      code:401,
      msg:'请携带token'
    });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.json({
        code:401,
        msg:'请携带有效token'
      });
    }
    req.user = user;
    next();
  });
}

module.exports={
  authenticateToken
}
